import { useRouter } from 'vue-router'
import { ProTableInstance } from '~/library/components/ProTable/interface'
import { HandleData } from './interface'

export const useHandleData = (
  api: (params: any) => Promise<any>,
  params: any,
  message: string,
  confirmType: HandleData.MessageType = 'warning'
) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(`是否${message}?`, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: confirmType,
      draggable: true,
    })
      .then(async () => {
        const res = await api(params)
        if (!res) return reject(false)
        ElMessage({
          type: 'success',
          message: `${message}成功!`,
        })
        resolve(true)
      })
      .catch(() => {})
  })
}

export const useDeleteData = async (api: (params: any) => Promise<any>, tableRef: ProTableInstance) => {
  if (tableRef.selectedListIds.length < 1) return ElMessage.error('请选择需要删除的数据')
  return new Promise(async (resolve, reject) => {
    useHandleData(api, { id: tableRef.selectedListIds }, '删除所选数据', 'warning')
      .then(() => {
        resolve(true)
        tableRef.getTableList()
        tableRef.clearSelection() // 删除后选中问题
      })
      .catch(() => {
        reject(false)
      })
  })
}

// export const useChangeDetailData = async (api: (params: any) => Promise<any>, params: any, go: string) => {
//   const router = useRouter()
//   const data = await api(params)
//   ElMessage.success(data.msg)
//   router.push(go)
// }

export function useHandleDetail() {
  const router = useRouter()
  const useChangeDetailData = async (api: (params: any) => Promise<any>, params: any, go: string) => {
    return new Promise<Boolean>(async (resolve, reject) => {
      try {
        const data = await api(params)
        ElMessage.success('成功')
        router.push(go) // 这里 router 一定有值
        resolve(true)
      } catch (err) {
        reject(false)
      }
    })
  }
  return {
    useChangeDetailData,
  }
}

export async function useHandleDialog(api: (params: any) => Promise<any>, params: any, getTableList: () => void) {
  return new Promise(async (resolve, reject) => {
    try {
      const data = await api(params)
      ElMessage.success(data.msg)
      resolve(true)
      getTableList()
    } catch (error) {
      reject(false)
    }
  })
}
